package org.bangumibuddy.mock.utils;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import lombok.SneakyThrows;
import org.testcontainers.shaded.com.fasterxml.jackson.databind.ObjectMapper;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.net.URL;
import java.util.*;

public class JsonConvertUtils<T> {
    Map map;

    @SneakyThrows
    public JsonConvertUtils(String path,Class classz) {
        URL resource = JsonConvertUtils.class.getResource(path);
        StringBuffer stringBuffer = new StringBuffer();
        Scanner scanner = new Scanner(resource.openStream());
        while (scanner.hasNextLine()){
            stringBuffer.append(scanner.nextLine());
        }

        //转为类
        Gson gson = new Gson();
        Type type = getMapType(classz);
        map = gson.fromJson(stringBuffer.toString(), type);
    }

    private Type getMapType(Class<?> classType) {
        return new ParameterizedType() {
            @Override
            public Type[] getActualTypeArguments() {
                return new Type[]{String.class, classType};
            }

            @Override
            public Type getRawType() {
                return Map.class;
            }

            @Override
            public Type getOwnerType() {
                return null;
            }
        };
    }

    public List<T> getAll()
    {
        List list = new ArrayList();
        map.forEach((k,v)->{
            list.add(v);
        });
        return list;
    }

    public Set<Map.Entry> getEntrys()
    {
        return map.entrySet();
    }

    public List<T> get(int size)
    {
        List list = new ArrayList();
        map.forEach((k,v)->{
            list.add(v);
        });
        return list.subList(0,size);
    }

    public T get(String key)
    {
        return (T) map.get(key);
    }
}
